<template>
  <div class="json-editor">
    <textarea ref="textarea" />
  </div>
</template>

<script>
import CodeMirror from 'codemirror'
import 'codemirror/addon/lint/lint.css'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/neat.css'
import 'codemirror/mode/javascript/javascript' // js 语法 高亮
import 'codemirror/mode/python/python' // python 语法 高亮
import 'codemirror/mode/sql/sql.js' // sql 语法 高亮
import 'codemirror/mode/groovy/groovy.js' // groovy 语法 高亮
import 'codemirror/addon/lint/lint'
import 'codemirror/addon/lint/json-lint' // json 错误校验
import 'codemirror/addon/lint/javascript-lint' // js 错误校验
import 'codemirror/addon/edit/matchbrackets' // 支持括号自动匹配
import 'codemirror/addon/edit/closebrackets' // 支持括号自动闭合
import 'codemirror/addon/selection/active-line.js' // 当前行高亮

require('script-loader!jsonlint')
window.JSHINT = require('jshint').JSHINT

export default {
  name: 'JsonEditor',
  /* eslint-disable vue/require-prop-types */
  props: {
    value: {
      default: ''
    },
    'mode': { // 当前语法模式。可选值：application/json, text/x-python, text/javascript, text/x-groovy, text/x-sql
      type: String,
      default: 'application/json'
    }
  },
  data() {
    return {
      jsonEditor: false
    }
  },
  watch: {
    value(value) {
      const editorValue = this.jsonEditor.getValue()
      if (value !== editorValue) {
        this.jsonEditor.setValue(JSON.stringify(this.value, null, 2))
      }
    }
  },
  mounted() {
    this.jsonEditor = CodeMirror.fromTextArea(this.$refs.textarea, {
      lineNumbers: true, // 是否显示行号
      mode: this.mode, // 语法模式
      gutters: ['CodeMirror-lint-markers'], // 在编辑器左侧显示语法错误
      lint: true, // 开启语法检测
      theme: 'neat', // 主题
      smartIndent: true, // 是否智能缩进
      indentUnit: 2, // 缩进单位，默认2
      matchBrackets: true, // 括号匹配显示
      autoCloseBrackets: true, // 自动闭合括号
      styleActiveLine: true // 高亮当前行
    })

    if (typeof this.value === 'object') {
      this.jsonEditor.setValue(JSON.stringify(this.value, null, 2))
    } else {
      this.jsonEditor.setValue(this.value)
    }
    this.jsonEditor.on('change', cm => {
      this.$emit('changed', cm.getValue())
      this.$emit('input', cm.getValue())
    })
  },
  methods: {
    // 获取编辑器内容
    getValue() {
      return this.jsonEditor.getValue()
    },
    // 设置编辑器内容
    setValue(value) {
      this.jsonEditor.setValue(value)
    },
    // 设置当前语法模式。可选值：application/json, text/x-python, text/javascript, text/x-groovy, text/x-sql
    setMode(mode) {
      this.jsonEditor.setOption('mode', mode)
    }
  }
}
</script>

<style lang="scss" scoped>
.json-editor {
  height: 100%;
  position: relative;

  ::v-deep {
    .CodeMirror {
      height: auto;
      min-height: 300px;
    }

    .CodeMirror-scroll {
      min-height: 300px;
    }

    .cm-s-rubyblue span.cm-string {
      color: #F08047;
    }
  }
}
</style>
